from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django import http
import random
import logging

from verifications.libs.captcha.captcha import captcha
from meiduo_mall.utils.response_code import RETCODE
from celery_tasks.sms import constants
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.
# 创建日志输出器
logging = logging.getLogger('django')


class SMScodeView(View):
    """短信验证码"""

    def get(self, request, mobile):
        """
        发送短信验证码
        :param mobile: 手机号
        :return: JSON
        """
        # 接收剩余参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 校验参数是否齐全
        if not all([image_code_client, uuid]):
            return http.HttpResponseForbidden('缺少必传参数')

        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        # 保存用户是否频繁发短信验证码
        # 提取短信验证码标记
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            # 存在提示频繁
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})

        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已失效'})
        # 提取之后就删除存储验证码
        redis_conn.delete('img_%s' % uuid)

        # 对比验证图形验证码
        # redis数据类型转换：bytes转字符串 并转小写
        image_code_client = image_code_client.lower()  # 转小写
        image_code_server = image_code_server.decode().lower()
        if image_code_server != image_code_client:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已失效'})

        # 生成短信验证码： 随机验证码
        # random.randint(100000, 999999)
        sms_code = '%06d' % random.randint(0, 999999)
        logging.info('sms_code_{} : {}'.format(mobile, sms_code))

        # # 保存验证码
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # # 保存短信验证码的标记
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 创建pipline管道
        pl = redis_conn.pipline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        # 发送短信验证码
        # 容联云通信代码  也可换用其他平台
        # 需要解耦 在celery/sms/tasks
        # res = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60],constants.SEND_SMS_TEMPLATE_ID)

        # 使用celery 发送短信验证码
        # send_sms_code(mobile, sms_code)  # 错误写法
        send_sms_code.delay(mobile, sms_code)   # 异步固定写法 使用delay调用

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功', 'data': {}})


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param uuid: 通用唯一识别码，用于唯一标识该图形验证码属于哪个用户的
        :return:image/jpg
        """
        # 实现业务逻辑
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)  # key  time  value
        # 响应结果
        return http.HttpResponse(image, content_type='image/jpg')
